'use strict';
const Service = require('egg').Service;
class GoodsService extends Service {
  async checkSku(data) {
    const res = this.app.mysql.select('product', {
      where: data,
    });
    if (res.length > 0) {
      console.log('res:', res);
    }
    return res;

  }
  async saveGoods(data) {
    const values = data.info;
    const specData = data.specData;
    const specValue = data.specValue;
    // const cateId = data.category_id;
    values.is_index = values.is_index ? 1 : 0;
    values.is_new = values.is_new ? 1 : 0;
    let goods_id = values.id;
    const gallery = values.gallery;


    // 更新
    if (goods_id > 0) {
      console.log('更新');
      // 更新商品
      await this.app.mysql.update('goods', {
        id: goods_id,
        category_id: values.category_id,
        is_on_sale: values.is_on_sale,
        name: values.name,
        sell_volume: values.sell_volume,
        goods_brief: values.goods_brief,
        goods_desc: values.goods_desc,
        sort_order: values.sort_order,
        is_index: values.is_index,
        is_new: values.is_new ? 1 : 0,
        goods_unit: values.goods_unit,
        list_pic_url: values.list_pic_url,
        freight_template_id: values.freight_template_id,
        specification_id: specValue,
      });
      // 更新购物车
      await this.app.mysql.query(`update cart set checked = '${values.is_on_sale}', is_on_sale = '${values.is_on_sale}',list_pic_url = '${values.list_pic_url}', freight_template_id = '${values.freight_template_id}' where goods_id = ${values.id}`);
      // 把产品列表中所有的产品，设置成删除，避免删除某条产品后，还能查到
      await this.app.mysql.query(`update product set is_delete = 1 where goods_id = ${values.id}`);

      // 重新添加产品
      for (const item of specData) {
        if (item.id > 0) {
          // await this.model('cart').where({
          //   product_id: item.id,
          //   is_delete: 0,
          // }).update({
          //   retail_price: item.retail_price,
          //   goods_specifition_name_value: item.value,
          //   goods_sn: item.goods_sn,
          // });
          // 更新购物车
          await this.app.mysql.query(`update cart set retail_price = '${item.retail_price}',goods_specifition_name_value = '${specValue}' ,goods_sn = '${item.goods_sn}' where product_id = '${item.id}' AND is_delete = 0`);
          item.is_delete = 0;
          await this.app.mysql.update('product', {
            id: item.id,
            spec_value: item.spec_value,
            goods_sn: item.goods_sn,
            goods_number: item.goods_number,
            retail_price: item.retail_price,
            cost: item.cost,
            goods_weight: item.goods_weight,
            has_change: 1,
            goods_name: item.goods_name,
            is_on_sale: 1,
            is_delete: 0,
          });

        } else {
          item.goods_id = values.id;
          await this.app.mysql.insert('product', item);
        }
      }
      for (const [ index, item ] of values.gallery.entries()) {
        if (item.is_delete === 1 && item.id > 0) {
          await this.app.mysql.update('goods_gallery', {
            id: item.id,
            id_delete: 1,
          });
        } else if (item.is_delete === 0 && item.id > 0) {
          await this.app.mysql.update('goods_gallery', {
            id: item.id,
            sort_order: index,
          });
        } else if (item.is_delete === 0 && item.id === 0) {
          await this.app.mysql.insert('goods_gallery', {
            goods_id: values.id,
            img_url: item.url,
            sort_order: index,
          });
        }
      }

    } else {
      // 新建
      // delete values.id;
      // delete values.gallery;
      // 把商品存数据库

      // 查询该商品是否存在

      const qGoodsRes = await this.app.mysql.select('goods', { where: { name: values.name } });
      if (qGoodsRes.length > 0) {
        return {
          code: 1,
        };
      }

      const goodsRes = await this.app.mysql.insert('goods', {
        category_id: values.category_id,
        is_on_sale: values.is_on_sale,
        name: values.name,
        sell_volume: values.sell_volume,
        goods_brief: values.goods_brief,
        goods_desc: values.goods_desc,
        sort_order: values.sort_order,
        is_index: values.is_index,
        is_new: values.is_new ? 1 : 0,
        goods_unit: values.goods_unit,
        list_pic_url: values.list_pic_url,
        freight_template_id: values.freight_template_id,
        is_delete: 0,
        specification_id: specValue,
      });
      goods_id = goodsRes.insertId;

      for (const item of specData) {

        await this.app.mysql.insert('product', {
          goods_id,
          is_on_sale: 1,
          goods_sn: item.goods_sn,
          goods_number: item.goods_number,
          retail_price: item.retail_price,
          cost: item.cost,
          goods_weight: item.goods_weight,
          goods_name: item.goods_name,
          spec_value: item.spec_value,
        });

      }

      // 存储轮播图
      values.gallery = gallery;
      // console.log('values.gallery:', values.gallery);
      for (let index = 0; index < values.gallery.length; index++) {
        const data = {
          goods_id,
          img_url: values.gallery[index].url,
          sort_order: index,
          is_delete: values.gallery[index].is_delete,
        };
        // 把data
        await this.app.mysql.insert('goods_gallery', data);
      }
    }

    // 更新商品总量
    const pro = await this.app.mysql.select('product', {
      where: {
        goods_id,
        is_on_sale: 1,
        is_delete: 0,
      },
    });
    console.log('pro:', pro);
    if (pro.length > 1) {
      const goodsNum = pro.reduce((pre, cur) => {
        return pre.goods_number + cur.goods_number;
      }, { goods_number: 0 });
      let maxPrice = pro[0].retail_price;
      let minPrice = pro[0].retail_price;
      let maxCost = pro[0].cost;
      let minCost = pro[0].cost;
      pro.forEach(item => {
        if (item.retail_price > maxPrice) {
          maxPrice = item.retail_price;
        }
        if (item.retail_price < minPrice) {
          minPrice = item.retail_price;
        }
        if (item.cost > maxCost) {
          maxCost = item.cost;
        }
        if (item.cost < minCost) {
          minCost = item.cost;
        }
      });
      let goodsPrice = '';
      if (maxPrice === minPrice) {
        goodsPrice = maxPrice;
      } else {
        goodsPrice = minPrice + '~' + maxPrice;
      }
      let costPrice = '';
      if (maxCost === minCost) {
        costPrice = maxCost;
      } else {
        costPrice = minCost + '~' + maxCost;
      }

      // console.log('update goods goods_id:', goods_id);
      const data = {
        id: goods_id,
        goods_number: goodsNum,
        retail_price: goodsPrice,
        cost_price: costPrice,
        min_retail_price: minPrice,
        min_cost_price: minCost,
      };
      // console.log('update goods data:', data);
      await this.app.mysql.update('goods', data);
    } else {
      if (pro[0]) {
        const info = {
          id: goods_id,
          goods_number: pro[0].goods_number,
          retail_price: pro[0].retail_price,
          cost_price: pro[0].cost,
          min_retail_price: pro[0].retail_price,
          min_cost_price: pro[0].cost,
        };

        // console.log('info:', info);
        await this.app.mysql.update('goods', info);
      }

    }
    // console.log('return goods_id：', goods_id);
    return {
      code: 0,
      data: { goods_id },
    };


  }
  async getGoodsList(data) {
    const inData = Object.assign({}, data);
    const page = inData.page || 1;
    const size = inData.size || 10;
    delete inData.page;
    delete inData.size;
    // const name = inData.name;
    const startIndex = (page - 1) * size;
    const endIndex = page * size;
    // 查询条件
    console.log('inData:', inData);
    const keys = Object.keys(inData);
    let queryKeyStr = 'is_delete = 0 AND';
    for (const key of keys) {
      if (key === 'name') {
        queryKeyStr += ' name like "%' + inData[key] + '%" AND';
      } else {
        queryKeyStr += ' ' + key + '=' + inData[key] + ' AND';
      }
    }
    queryKeyStr = queryKeyStr.slice(0, -3);

    if (queryKeyStr.length === 0) {
      queryKeyStr = 'name like "%%"';
    }

    // console.log('queryKeyStr:', queryKeyStr);

    // 根据名称搜索商品
    const querySql = `select * from goods where ${queryKeyStr} limit ${startIndex},${endIndex}`;
    const goods = await this.app.mysql.query(querySql);

    const totalRes = await this.app.mysql.query(`select count(*) as total from goods where ${queryKeyStr}`);
    console.log('getGoodsList totalRes:', totalRes);
    const total = totalRes[0].total;
    // console.log('getGoodsList goods:', goods);
    const productPromiseArr = goods.map(async item => {
      // console.log('item:', item);
      return await this.app.mysql.select('product', { where: {
        goods_id: item.id,
      } });
    });
    // 同一个商品可能有多个product,productArr 是一个二维数组 [[{},{}],[{}]]
    const productArr = await Promise.all(productPromiseArr);

    goods.forEach((item, index) => {
      item.product = productArr[index];
    });
    return {
      list: goods,
      page,
      size,
      total,
    };
  }
  async getGoodsById(id) {
    const goodsArr = await this.app.mysql.select('goods', { where: { id } });
    // console.log('goods:', goods);
    const goods = goodsArr[0];
    const product = await this.app.mysql.select('product', { where: { goods_id: id } });
    const gallery = await this.app.mysql.select('goods_gallery', { where: { goods_id: id } });
    if (goods) {
      goods.product = product;
      goods.gallery = gallery;
    }
    return goods;

  }
  // 更新排序
  async updateGoods(data) {
    const res = await this.app.mysql.update('goods', data);
    return res;
  }
  async updateProduct(data) {
    const goods_id = data.goods_id;
    const res = await this.app.mysql.update('product', data);
    // 更新商品总量
    const pro = await this.app.mysql.select('product', {
      where: {
        goods_id,
        is_on_sale: 1,
        is_delete: 0,
      },
    });
    console.log('updateProduct pro:', pro);
    if (pro.length > 1) {
      const goodsNum = pro.reduce((pre, cur) => {
        return pre.goods_number + cur.goods_number;
      }, { goods_number: 0 });
      let maxPrice = pro[0].retail_price;
      let minPrice = pro[0].retail_price;
      let maxCost = pro[0].cost;
      let minCost = pro[0].cost;
      pro.forEach(item => {
        if (item.retail_price > maxPrice) {
          maxPrice = item.retail_price;
        }
        if (item.retail_price < minPrice) {
          minPrice = item.retail_price;
        }
        if (item.cost > maxCost) {
          maxCost = item.cost;
        }
        if (item.cost < minCost) {
          minCost = item.cost;
        }
      });
      let goodsPrice = '';
      if (maxPrice === minPrice) {
        goodsPrice = maxPrice;
      } else {
        goodsPrice = minPrice + '~' + maxPrice;
      }
      let costPrice = '';
      if (maxCost === minCost) {
        costPrice = maxCost;
      } else {
        costPrice = minCost + '~' + maxCost;
      }

      // console.log('update goods goods_id:', goods_id);
      const data = {
        id: goods_id,
        goods_number: goodsNum,
        retail_price: goodsPrice,
        cost_price: costPrice,
        min_retail_price: minPrice,
        min_cost_price: minCost,
      };
      // console.log('update goods data:', data);
      await this.app.mysql.update('goods', data);
    } else {
      if (pro[0]) {
        const info = {
          id: goods_id,
          goods_number: pro[0].goods_number,
          retail_price: pro[0].retail_price,
          cost_price: pro[0].cost,
          min_retail_price: pro[0].retail_price,
          min_cost_price: pro[0].cost,
        };

        // console.log('info:', info);
        await this.app.mysql.update('goods', info);
      }

    }
    return res;
  }
  async deleteGoodsById(id) {

    const res = await this.app.mysql.update('goods', { id, is_delete: 1 });
    if (res.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };


  }
}

module.exports = GoodsService;
